<template>
  <div>
    <div v-if="editable" class="crud-opts">
      <el-button
        class="filter-item"
        size="mini"
        type="primary"
        icon="el-icon-plus"
        @click="doSelectItem">选择检测物料</el-button>
      <el-button
        class="filter-item"
        size="mini"
        type="danger"
        icon="el-icon-delete"
        @click="doDeleteItem">删除</el-button>
      <el-checkbox v-model="scanFlag" style="padding-left:10px;">扫描录入</el-checkbox>
      <span v-if="scanFlag">
        批次数:<el-input-number v-model.number="scanQty" :controls="false" :precision="2" size="mini" style="width: 80px;" />
        条形码:<el-input ref="scanItemId" v-model="scanItemId" clearable placeholder="扫描物料条形码" style="width: 200px;" class="filter-item" size="mini" @keyup.enter.native="scanItemInput"/>
      </span>
      <base-item-select-list ref="baseItemSelectList" :multi-select="true" @itemSelectCallback="itemSelectCallback" />
    </div>
    <DataGridTable
      :data="qcDetails"
      :show-page="false"
      size="mini"
      height="200"
      max-height="500px"
      style="width: 100%"
      @row-click="viewQcDetailCheck"
      @selection-change="handleSelectionChange">
      <el-table-column prop="itemCode" label="物料编号"/>
      <el-table-column label="物料名称" prop="itemName" show-overflow-tooltip/>
      <el-table-column label="批次数" width="100" prop="sampleQty">
        <template slot-scope="scope">
          <el-input-number v-model.number="scope.row.sampleQty" :disabled="!editable" :controls="false" :precision="2" size="mini" style="width: 100%" @change="setQcQty(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="抽样检查数" width="100" prop="qcQty">
        <template slot-scope="scope">
          <el-input-number v-model.number="scope.row.qcQty" :disabled="!editable" :controls="false" :min="0" :precision="2" size="mini" style="width: 100%" />
        </template>
      </el-table-column>
      <el-table-column label="检验结果">
        <template slot-scope="scope">
          <el-select v-model="scope.row.qcResult" :disabled="!editable" style="width:100px;" size="mini" filterable placeholder="检验结果">
            <el-option
              v-for="(item) in dicts.qc_result"
              :key="item.id"
              :label="item.dictName"
              :value="item.dictCode"/>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="合格数" width="100" prop="qcPassQty">
        <template slot-scope="scope">
          <el-input-number v-model.number="scope.row.qcPassQty" :disabled="!editable" :controls="false" :min="0" :precision="2" size="mini" style="width: 100%" @change="passQtyChange(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="不合格数" width="100" prop="qcUnpassQty">
        <template slot-scope="scope">
          <el-input-number v-model.number="scope.row.qcUnpassQty" :disabled="!editable" :controls="false" :min="0" :precision="2" size="mini" style="width: 100%" @change="unpassQtyChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="不合格数处理">
        <template slot-scope="scope">
          <el-select v-model="scope.row.qcUnpassResult" :disabled="!editable" style="width:100px;" size="mini" filterable placeholder="不合格数处理">
            <el-option
              v-for="(item) in dicts.qc_unpass_result"
              :key="item.id"
              :label="item.dictName"
              :value="item.dictCode"/>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="单位">
        <template slot-scope="scope">
          <template v-for="item in dicts.item_unit">
            <span v-if="scope.row.unit && scope.row.unit === item.dictCode" :key="item.id" >{{ item.dictName }}</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="规格" prop="itemSpec" show-overflow-tooltip />
      <el-table-column label="品牌" prop="itemBrand" show-overflow-tooltip />
      <el-table-column label="备注" width="100">
        <template slot-scope="scope">
          <el-input v-model="scope.row.rmk" :disabled="!editable" size="mini" style="width: 100%"/>
        </template>
      </el-table-column>
      <el-table-column label="订单号" prop="orderCode" show-overflow-tooltip />
      <el-table-column label="采购单号" prop="poCode" show-overflow-tooltip />
    </DataGridTable>
    <el-table
      :data="curQcDetail.detailCheckList"
      :multi-select="false"
      :show-page="false"
      size="mini">
      <el-table-column v-if="editable" label="操作" width="100">
        <template slot="header" class="clearfix">
          <el-button
            icon="el-icon-plus"
            size="mini"
            type="primary"
            @click="addDetailCheck">添加</el-button>
        </template>
        <template slot-scope="scope">
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column :label="'检验项目(' + (curItemCode || '请选择明细') + ')'" width="220">
        <template slot-scope="scope">
          <el-input v-model="scope.row.checkItem" :disabled="!editable" size="mini" style="width: 100%"/>
        </template>
      </el-table-column>
      <el-table-column label="极严重数" width="100" prop="crQty">
        <template slot-scope="scope">
          <el-input-number v-model.number="scope.row.crQty" :disabled="!editable" :controls="false" :precision="2" size="mini" style="width: 100%" />
        </template>
      </el-table-column>
      <el-table-column label="严重数" width="100" prop="majQty">
        <template slot-scope="scope">
          <el-input-number v-model.number="scope.row.majQty" :disabled="!editable" :controls="false" :precision="2" size="mini" style="width: 100%" />
        </template>
      </el-table-column>
      <el-table-column label="轻微数" width="100" prop="minQty">
        <template slot-scope="scope">
          <el-input-number v-model.number="scope.row.minQty" :disabled="!editable" :controls="false" :precision="2" size="mini" style="width: 100%" />
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="rmk">
        <template slot-scope="scope">
          <el-input v-model="scope.row.rmk" :disabled="!editable" size="mini" style="width: 100%"/>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import BaseItemSelectList from '@/views/base/item/module/baseItemSelectList'
import baseItem from '@/api/base/BaseItem'

export default {
  dictTypes: ['item_unit', 'qc_result', 'qc_unpass_result'],
  components: { BaseItemSelectList },
  props: {
    qcDetails: {
      type: Array,
      required: true
    },
    editable: {
      type: Boolean,
      default: false,
      required: false
    },
    supForm: {
      type: Object,
      default: null,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      scanFlag: false,
      scanItemId: null,
      scanQty: 10,
      selectedDetailRows: [],
      curQcDetail: {
        detailCheckList: []
      },
      curItemCode: '',
      style: 'width: 150px'
    }
  },
  watch: {
    qcDetails: {
      handler(val) {
        const _this = this
        const curNum = _this.curQcDetail ? _this.curQcDetail.num : null
        if (_this.qcDetails && _this.qcDetails.length > 0) {
          if (curNum) {
            const tmpqcdetails = _this.qcDetails.filter(tmpdetail => tmpdetail.num === curNum)
            _this.setCurQcDetailData(tmpqcdetails.length > 0 ? tmpqcdetails[0] : {})
          } else {
            _this.setCurQcDetailData(_this.qcDetails[0])
          }
        } else {
          _this.setCurQcDetailData({})
        }
      },
      immediate: true
    }
  },
  methods: {
    getMaxDetailNum() {
      let detailNum = 0
      this.qcDetails.forEach(tmprow => {
        if (tmprow.num > detailNum) {
          detailNum = tmprow.num
        }
      })
      return detailNum
    },
    handleSelectionChange(val) {
      this.selectedDetailRows = val
    },
    viewQcDetailCheck(row, column, event) {
      if (row) {
        this.setCurQcDetailData(row)
        return
      }
      this.setCurQcDetailData({})
    },
    setCurQcDetailData(qcDetailData) {
      this.curQcDetail = qcDetailData
      if (!this.curQcDetail.detailCheckList) {
        this.curQcDetail.detailCheckList = []
      }
      this.curItemCode = qcDetailData ? qcDetailData.itemCode : ''
    },
    doSelectItem() {
      const _thisform = this.$refs.baseItemSelectList
      _thisform.initLoadData()
    },
    doDeleteItem() {
      let tmpDetails = JSON.parse(JSON.stringify(this.qcDetails))
      this.selectedDetailRows.forEach(tmprow => {
        tmpDetails = tmpDetails.filter(vo => vo.num !== tmprow.num)
      })
      this.$emit('setDetails', tmpDetails)
    },
    doCopyItem() {
      const tmpDetails = JSON.parse(JSON.stringify(this.qcDetails))
      let detailNum = this.getMaxDetailNum()
      this.selectedDetailRows.forEach(tmprow => {
        const addRow = JSON.parse(JSON.stringify(tmprow))
        detailNum++
        addRow.id = null
        addRow.detailLotNo = null
        addRow.num = detailNum
        tmpDetails.push(addRow)
      })
      this.$emit('setDetails', tmpDetails)
    },
    itemSelectCallback(selectedRows, sourceObject) {
      const allKeys = []
      const tmpDetails = JSON.parse(JSON.stringify(this.qcDetails))
      tmpDetails.forEach(tmprow => {
        allKeys[tmprow.itemId] = true
      })
      let detailNum = this.getMaxDetailNum()
      selectedRows.forEach(tmprow => {
        if (!allKeys[tmprow.id]) {
          detailNum++
          const addRow = {}
          addRow.itemId = tmprow.id
          addRow.unit = tmprow.stockUnit
          addRow.itemCode = tmprow.itemCode
          addRow.itemName = tmprow.itemName
          addRow.itemSpec = tmprow.itemSpec
          addRow.itemBrand = tmprow.itemBrand
          addRow.qcResult = 'pass'
          addRow.sampleQty = 10
          this.setQcQty(addRow)
          addRow.id = null
          addRow.num = detailNum
          tmpDetails.push(addRow)
        }
      })
      this.$emit('setDetails', tmpDetails)
      sourceObject.cancel()
    },
    scanItemInput() {
      const itemId = this.scanItemId
      const allKeys = []
      const tmpDetails = JSON.parse(JSON.stringify(this.qcDetails))
      tmpDetails.forEach(tmprow => {
        allKeys[tmprow.itemId] = true
      })
      if (allKeys[itemId]) {
        this.$notify({
          title: '该物料已存在',
          type: 'info',
          duration: 2500
        })
        return
      }
      let detailNum = this.getMaxDetailNum()
      detailNum++
      baseItem.getItemInfoById(itemId).then(res => {
        const tmpItem = res.data
        if (!tmpItem) {
          this.$notify({
            title: '物料不存在',
            type: 'info',
            duration: 2500
          })
          return
        }
        const addRow = {}
        addRow.itemId = tmpItem.id
        addRow.unit = tmpItem.stockUnit
        addRow.itemCode = tmpItem.itemCode
        addRow.itemName = tmpItem.itemName
        addRow.itemSpec = tmpItem.itemSpec
        addRow.itemBrand = tmpItem.itemBrand
        addRow.sampleQty = this.scanQty
        addRow.qcResult = 'pass'
        addRow.id = null
        addRow.num = detailNum
        this.setQcQty(addRow)
        tmpDetails.push(addRow)
        this.$emit('setDetails', tmpDetails)

        this.scanItemId = null
        this.$refs.scanItemId.focus()
      })
    },
    setQcQty(qcDetailRow) {
      const busMainData = this.supForm.form.busMainData
      qcDetailRow.qcQty = busMainData.sampleMethod === 'ratio' ? (qcDetailRow.sampleQty * busMainData.sampleQtyRatio / 100)
        : (qcDetailRow.sampleQty > busMainData.sampleQtyRatio ? busMainData.sampleQtyRatio : qcDetailRow.sampleQty)
    },
    passQtyChange(qcDetailRow) {
      qcDetailRow.qcUnpassQty = qcDetailRow.qcQty - qcDetailRow.qcPassQty
    },
    unpassQtyChange(qcDetailRow) {
      qcDetailRow.qcPassQty = qcDetailRow.qcQty - qcDetailRow.qcUnpassQty
    },
    addDetailCheck() {
      const _this = this
      if (!_this.curItemCode) {
        _this.$notify({
          title: '请选择检测物料',
          type: 'info',
          duration: 2500
        })
        return
      }
      let tmpDetails = _this.curQcDetail.detailCheckList
      if (!tmpDetails) {
        tmpDetails = []
        _this.curQcDetail.detailCheckList = tmpDetails
      }
      const addRow = { crQty: 0, majQty: 0, minQty: 0 }
      tmpDetails.push(addRow)
      const tmpQcDetails = JSON.parse(JSON.stringify(_this.qcDetails))
      tmpQcDetails.forEach(tmpobj => {
        if (_this.curQcDetail.num === tmpobj.num) {
          tmpobj = _this.curQcDetail
          return
        }
      })
      this.$emit('setDetails', tmpQcDetails)
    },
    handleDelete(index, row) {
      const tmpDetails = this.curQcDetail.detailCheckList
      tmpDetails.splice(index, 1)
    }
  }
}
</script>
